// WorldScene.js

class WorldScene {
    constructor() {
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.controls = null;
        this.labelRenderer = null;
    }

    async initScene(container) {
        if (!container) {
            throw new Error('Container element is required');
        }

        if (container.clientWidth === 0 || container.clientHeight === 0) {
            console.log('Container sizes are 0, retrying in 100ms');
            return new Promise(resolve => {
                setTimeout(() => this.initScene(container).then(resolve), 100);
            });
        }

        console.log("Init world scene");

        // 1. 初始化场景
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0xE6E6E6);

        // 2. 设置相机
        const aspect = container.clientWidth / container.clientHeight;
        this.camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 7000);
        /*
        this.camera.position.set(
            robotPose.worldX + worldUnitsManager.metersToUnits(0.4),
            worldUnitsManager.metersToUnits(0.5),
            robotPose.worldZ + worldUnitsManager.metersToUnits(0.2)
        );
        */
        this.camera.position.set(
            robotPose.worldX + worldUnitsManager.metersToUnits(1.5),
            worldUnitsManager.metersToUnits(3),
            robotPose.worldZ + worldUnitsManager.metersToUnits(1)
        );

        // 3. 设置渲染器
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
        this.renderer.setSize(container.clientWidth, container.clientHeight);
        container.appendChild(this.renderer.domElement);

        // 4. 初始化控制器
        this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
        this.initOrbitControls();

        // 5. 添加地图模型
        const mapModel = this.createMapModel();
        this.scene.add(mapModel);

        // 6. 初始化标签渲染器
        this.labelRenderer = this.initCSS2DRenderer(container);

        // 7. 添加光源
        this.addLights();

        console.log("Creating robot model...");
        if (!window.robotModel) {
            throw new Error('RobotModel is not initialized');
        }
        // 8. 创建机器人模型
        const robotInstance = window.robotModel.createRobotModel(window.robotConfig);
        // 确保组件管理器能访问到所有组件
        window.componentManager.setRobot(window.robotModel);
        // 应用世界单位缩放
        const scale = worldUnitsManager.UNIT_SCALE;
        robotInstance.scale.set(scale, scale, scale);
        this.scene.add(robotInstance);

        // 9. 开始动画循环
        this.animate();

        return new Promise(resolve => resolve());
    }

    initOrbitControls() {
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.05;
        this.controls.minDistance = worldUnitsManager.metersToUnits(0.5);
        this.controls.maxDistance = worldUnitsManager.metersToUnits(10);
        this.controls.enableRotate = true;
        this.controls.rotateSpeed = 0.5;
        this.controls.enableZoom = true;
        this.controls.zoomSpeed = 1.0;
        this.controls.enablePan = true;
        this.controls.panSpeed = 1.0;
    }

    createMapModel() {
        const mapGenerator = new EnhancedMapGenerator();
        return mapGenerator.createMapModel();
        return mapModel;
    }

    initCSS2DRenderer(container) {
        const labelRenderer = new THREE.CSS2DRenderer();
        labelRenderer.setSize(container.clientWidth, container.clientHeight);
        labelRenderer.domElement.style.position = 'absolute';
        labelRenderer.domElement.style.top = '0px';
        labelRenderer.domElement.style.pointerEvents = 'none';
        container.appendChild(labelRenderer.domElement);
        return labelRenderer;
    }

    addLights() {
        const ambientLight = new THREE.AmbientLight(0xbbbbbb);
        this.scene.add(ambientLight);
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.4);
        directionalLight.position.set(5, 5, 5);
        this.scene.add(directionalLight);
    }

    animate() {
        requestAnimationFrame(() => this.animate());

        // 更新控制器
        if (this.controls) {
            this.controls.update();
        }

        // 更新组件动画
        if (window.componentManager) {
            window.componentManager.updateAnimations();
        }

        // 渲染场景
        if (this.renderer && this.scene && this.camera) {
            this.renderer.render(this.scene, this.camera);
        }
        if (this.labelRenderer) {
            this.labelRenderer.render(this.scene, this.camera);
        }
    }

    updateSceneSizes() {
        const container = this.renderer.domElement.parentElement;
        if (!container) return;

        const width = container.clientWidth;
        const height = container.clientHeight;

        if (this.camera) {
            this.camera.aspect = width / height;
            this.camera.updateProjectionMatrix();
        }

        if (this.renderer) {
            this.renderer.setSize(width, height);
        }

        if (this.labelRenderer) {
            this.labelRenderer.setSize(width, height);
        }
    }

    // 获取场景实例
    getScene() {
        return this.scene;
    }

    // 获取相机实例
    getCamera() {
        return this.camera;
    }

    // 获取渲染器实例
    getRenderer() {
        return this.renderer;
    }
}

// 创建全局单例
const worldScene = new WorldScene();

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.worldScene = worldScene;
    window.WorldScene = WorldScene;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        WorldScene,
        worldScene
    };
}